package com.googlecode.monitoring.flash.jobs;

import com.googlecode.monitoring.config.SpringApplicationContext;
import com.googlecode.monitoring.dao.AgentConfigurationDao;
import com.googlecode.monitoring.dao.AgentStatusDao;
import com.googlecode.monitoring.flash.model.FlashItemToCheck;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.StateName;
import com.googlecode.monitoring.service.DefaultEmailService;
import com.googlecode.monitoring.service.MonitoringService;
import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class FlashPingJob extends QuartzJobBean {
    Logger log = Logger.getLogger(FlashPingJob.class);
    private DefaultEmailService emailService;
    private AgentStatusDao flashAgentStatusDao;
    private AgentConfigurationDao flashAgentConfigurationDao;
    private MonitoringService monitoringService;

    public FlashPingJob() {
        emailService = SpringApplicationContext.getBean(DefaultEmailService.class);
        flashAgentStatusDao = SpringApplicationContext.getBean(AgentStatusDao.class);
        flashAgentConfigurationDao =  SpringApplicationContext.getBean(AgentConfigurationDao.class);
        monitoringService = SpringApplicationContext.getBean(MonitoringService.class);
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        FlashItemToCheck flashItemToCheck = (FlashItemToCheck) dataMap.get("item");
        boolean testfailed = monitoringService.checkIsItemOutdated(flashItemToCheck);
        if (testfailed) {
            ItemToCheck wsItemFromReport = flashAgentStatusDao.getItemFromCheckReport(flashItemToCheck);
            if (wsItemFromReport == null || !wsItemFromReport.getCurrentStateName().equals(StateName.EMAIL_SENT)) {
                emailService.sendAlertEmail(flashItemToCheck, flashAgentConfigurationDao.getCommonResponsiblePersons());
                log.warn("The " + flashItemToCheck.getName() + " service is DOWN, an alert email is sent");
            }
            flashItemToCheck.switchState(com.googlecode.monitoring.model.StateName.EMAIL_SENT);
        }
        flashAgentStatusDao.saveItemToCheckReport(flashItemToCheck);

    }
}
